package com.hujiang.basic.search.zookeeper.zkNotify;

import com.hujiang.basic.search.handler.HandlerService;
import com.hujiang.basic.search.handler.impl.model.HandlerInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zhanglibin on 2017/3/22.
 */
@Slf4j
@Component
public class DistributedNotifyClient {

    public Map<String, DistributedNotify> distributedNotifyMap = new HashMap<>();

    @Value(value = "${zk.url}")
    private String zkUrl;

    @Value(value = "${zk.notify.prefix}")
    private String notifyPrefix;

    @Autowired
    private HandlerService service;

    @PostConstruct
    @Scheduled(fixedRate = 60_000)
    private void initZookeeperNotifyClient() {
        List<HandlerInfo> queues = service.query();
        if (CollectionUtils.isEmpty(queues)) {
            log.info("no queue when init zookeeper client");
            return;
        }
        queues.forEach((q) -> {
                    if (StringUtils.isEmpty(q.getAlias()) || distributedNotifyMap.containsKey(q.getAlias())){
                        return;
                    }
                    String notifyZkPath = notifyPrefix + q.getAlias();
                    String queue = q.getQueue();
                    DistributedNotify distributedNotify = new DistributedNotify();
                    try {
                        distributedNotify.initCuratorClient(zkUrl, notifyZkPath, queue, service);
                        distributedNotifyMap.put(q.getAlias(), distributedNotify);
                        log.info("init  distributed Notify client:{} success",q.getAlias());
                    } catch (Exception ex) {
                        log.error("error when init CuratorClient ", ex);
                    }
                }
        );
    }

}
